/*
 * @Copyright: Copyright (c) 2030 吴周海
 * @Author: wzh200x@126.com
 * @Date: 2025-10-09 10:33:09
 * @LastEditors: wzh200x@126.com
 * @LastEditTime: 2025-10-28 11:20:19
 * @FilePath: \gogamewebserver\goGameWebServer\internal\cmd\cmd.go
 * @Description: 文件功能描述
 */
package cmd

import (
	"context"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/gcmd"

	"goGameWebServer/internal/common/config"
	"goGameWebServer/internal/controller/account"
	"goGameWebServer/internal/controller/admin"
	"goGameWebServer/internal/controller/auth"
	"goGameWebServer/internal/controller/avatar"
	"goGameWebServer/internal/controller/cdkey"
	"goGameWebServer/internal/controller/center"
	gameconfig "goGameWebServer/internal/controller/game_config"
	"goGameWebServer/internal/controller/hello"
	"goGameWebServer/internal/controller/report"
	"goGameWebServer/internal/controller/server"
	servertime "goGameWebServer/internal/controller/server_time"
	"goGameWebServer/internal/middlewares"
)

// 定义用于保护 Swagger/OpenAPI 文档的 BasicAuth 钩子函数
func swaggerBasicAuth(r *ghttp.Request) {
	// BasicAuth 方法会检查请求头。如果认证失败，会自动返回 401 响应并弹出认证对话框
	if !r.BasicAuth(config.AppOptions.SwaggerAccount, config.AppOptions.SwaggerPassword, "") {
		// 如果认证失败，阻止请求继续处理
		r.ExitAll()
		return
	}
	// 认证成功，继续处理请求
}

var (
	Main = gcmd.Command{
		Name:  "main",
		Usage: "main",
		Brief: "start http server",
		Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
			s := g.Server()
			s.SetPort(config.AppOptions.ServerPort)
			s.Use(middlewares.MiddlewareCORS)
			s.Use(middlewares.SignatureMiddleware)
			s.Use(middlewares.UnifiedResponseMiddleware)
			if config.AppOptions.Swagger {
				// 设置 OpenAPI 规范文件访问路径
				s.SetOpenApiPath("/api.json")
				// 启用内置的 Swagger UI 接口文档，访问路径为 /swagger
				s.SetSwaggerPath("/swagger")
				// 保护 Swagger UI 页面
				s.BindHookHandler("/swagger"+"/*", ghttp.HookBeforeServe, swaggerBasicAuth)
				// 保护 OpenAPI JSON 文件
				s.BindHookHandler("/api.json", ghttp.HookBeforeServe, swaggerBasicAuth)
			}
			s.Group("/", func(group *ghttp.RouterGroup) {
				group.Bind(
					hello.NewV1(),
				)
			})
			s.Group("/v1/public", func(group *ghttp.RouterGroup) {
				group.Bind(
					servertime.NewV1(),
					server.NewV1(),
					auth.NewV1(),
					center.NewV1(),
					gameconfig.NewV1(),
					cdkey.NewV1(),
					admin.NewV1(),
				)
			})

			s.Group("/v1/private", func(group *ghttp.RouterGroup) {
				group.Middleware(middlewares.MiddlewareJWTRequired)
				group.Bind(
					auth.NewV1Private(),
					avatar.NewV1Private(),
					cdkey.NewV1Private(),
					account.NewV1Private(),
					report.NewV1Private(),
				)
			})
			s.Run()
			return nil
		},
	}
)
